import { takeEvery, put } from 'redux-saga/effects'
import { ADD_PRODUCT_TO_CART, ADD_PRODUCT_TO_LOCALCART, GET_CARTS,
   SET_CARTS, DELETE_CART, DELETE_CART_FROM_LOCAL, CHANGE_CART_COUNT, CHANGE_LOCAL_CART_COUNT } from '../actions/cart.action'
import axios from 'axios'

function* addProductToCart(action) {
  const { data } = yield axios.post('http://localhost:3005/cart/add', { gid: action.payload })
  yield put(ADD_PRODUCT_TO_LOCALCART(data))
}

function* getCarts() {
  const { data } = yield axios.get('http://localhost:3005/cart')
  yield put(SET_CARTS(data))
}

function* deleteCart(action) {

  const { status } = yield axios.delete('http://localhost:3005/cart/delete', { params: { cid: action.payload.id }})
  console.log(action, status, 'delete data')
  if (status === 200)
    yield put(DELETE_CART_FROM_LOCAL(action.payload.index))
}

function* changeCartCount(action) {
  const { data } = yield axios.put('http://localhost:3005/cart', { cid: action.payload.id, count: action.payload.count })
  yield put(CHANGE_LOCAL_CART_COUNT(data))
}

export default function* cartSaga() {
  yield takeEvery(ADD_PRODUCT_TO_CART, addProductToCart)
  yield takeEvery(GET_CARTS, getCarts)
  yield takeEvery(DELETE_CART, deleteCart)
  yield takeEvery(CHANGE_CART_COUNT, changeCartCount)
}